package com.zrj.auth.core.extensions.mobile;

import com.zrj.auth.core.userdetails.mobile.MemberUserDetails;
import com.zrj.auth.core.userdetails.mobile.MemberUserDetailsServiceImpl;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.HashSet;

/**
 *  短信验证码授权提供者
 * @author zhaorujie
 */
@Data
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private MemberUserDetailsServiceImpl userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthenticationToken smsCodeAuthenticationToken = (SmsCodeAuthenticationToken) authentication;
        String mobile = (String) smsCodeAuthenticationToken.getPrincipal();
        String code = (String) smsCodeAuthenticationToken.getCredentials();
        if (!"666666".equals(code)) {
            throw new RuntimeException("验证码不正确");
        }
        UserDetails userDetails = userDetailsService.loadUserByMobile(mobile);
        SmsCodeAuthenticationToken result = new SmsCodeAuthenticationToken(userDetails, authentication.getCredentials(), new HashSet<>());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
